package edu.lsnu.equipment_management_system.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import edu.lsnu.equipment_management_system.pojo.domain.JsonData;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.*;
import java.util.HashMap;

/**
 * @author mzy
 * @Description
 * @date 2018/12/2
 */
@RestController
public class ChatController {
    private static ObjectMapper MAPPER = new ObjectMapper();

    // private String apiKey = "6c176da65cf24d96a46c3ce5f3397850";
    private String userId ="359303";
    private String urlPath = "http://openapi.tuling123.com/openapi/api/v2";
    private String chatInfo = "";
    private String chatJsonBefore = "{\n" +
            "\t\t\t\t\t\t\"reqType\":0,\n" +
            "\t\t\t\t\t    \"perception\": {\n" +
            "\t\t\t\t\t        \"inputText\": {\n" +
            "\t\t\t\t\t            \"text\": \"";

    private String chatJsonAfter = "\"\n" +
            "\t\t\t\t\t        },\n" +
            "\t\t\t\t\t    },\n" +
            "\t\t\t\t\t    \"userInfo\": {\n" +
            "\t\t\t\t\t        \"apiKey\": \"apiKeyVal\",\n" +
            "\t\t\t\t\t        \"userId\": \""+userId+"\"\n" +
            "\t\t\t\t\t    }\n" +
            "\t\t\t\t\t}";

    @PostMapping("/bingo/chat")
    public Object chart(@RequestParam(defaultValue = "") String msg, String apiKey){
        if (apiKey == null || "".equals(apiKey)) {
            return JsonData.buildError("出错了~");
        }

        BufferedReader reader = null;
        String result = "";
        try {
            URL url = new URL(urlPath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            // 设置文件类型:
            conn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
            // 设置接收类型否则返回415错误
            conn.setRequestProperty("accept","application/json");
            // 往服务器里面发送数据
            // if (msg != null && !"".equals(msg)) {
            chatInfo = msg;
            chatJsonAfter = chatJsonAfter.replaceFirst("apiKeyVal", apiKey);
            String chatJson = chatJsonBefore + chatInfo + chatJsonAfter;
            byte[] writebytes = chatJson.getBytes();
            // 设置文件长度
            conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
            OutputStream outwritestream = conn.getOutputStream();
            outwritestream.write(chatJson.getBytes());
            outwritestream.flush();
            outwritestream.close();

            if (conn.getResponseCode() == 200) {
                reader = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                result = reader.readLine();
            }
            // }
            ObjectMapper mapper = new ObjectMapper();
            JsonNode node = mapper.readTree(result);
            JsonNode res_node = node.path("results");
            JsonNode gro_node = res_node.path(0);
            JsonNode val_node = gro_node.path("values");
            JsonNode tex_node = val_node.path("text");




            // System.out.println(node);
            // System.out.println(res_node);
            // System.out.println(gro_node);
            // System.out.println(val_node);
            // System.out.println(tex_node);
            // System.out.println(tex_node.asText());

            result = tex_node.asText();
            /*
            HashMap<Object,Object> resultMap = MAPPER.readValue(result, HashMap.class);
            // String results = resultMap.get("results");
            // System.out.println(results);
            System.out.println(resultMap);
            int index = result.lastIndexOf("text");

            result = result.substring(index + 6); // + 5顺便去掉 text:
            result = result.replaceAll("\"", "");
            result = result.replaceAll("}", "");
            result = result.replaceAll("]", "");
            result = result.replaceAll("", "");
            System.out.println(result);
            */
        } catch (ProtocolException e1) {
            JsonData.buildError("出错了~");
        } catch (MalformedURLException e1) {
            JsonData.buildError("出错了~");
        } catch (IOException e1) {
            JsonData.buildError("出错了~");
        }

        return JsonData.buildSuccess(0, result, "操作成功！");
    }
}
